package com.zhdl.hardware_contact.hardware_common.service.impl;

import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.project.network.entity.PortComm;
import com.project.network.entity.PortSocket;
import com.project.network.enums.Status;
import com.zhdl.common.ytools.BaseConversionTools;
import com.zhdl.common.ytools.S7Config;
import com.zhdl.common.ytools.springContext.request.CommonParamOptReq;
import com.zhdl.hardware_contact.hardware_common.param.CurrencyProtocolWriteReq;
import com.zhdl.hardware_contact.hardware_common.repository.CurrencyProtocolCmdHandleService;
import com.zhdl.hardware_contact.hardware_common.repository.TCPIPCmdHandleService;
import com.zhdl.hardware_contact.hardware_common.service.CurrencyCmdSendService;
import com.zhdl.modules.common.protocol_param.service.ProtocolParamService;
import com.zhdl.network.strategy.common_client.dto.SendReceiverData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.zhdl.common.ytools.springContext.CommonParmaOpt.*;

@Slf4j
@Service("CurrencyCmdSendServiceImpl")
public class CurrencyCmdSendServiceImpl implements CurrencyCmdSendService {

    //注入协议参数
    @Resource
    private ProtocolParamService protocolParamService;

    @Resource
    @Qualifier("TCPProtocolCmdHandleServiceImpl")
    private CurrencyProtocolCmdHandleService tcpProtocolCmdHandleService;

    @Resource
    @Qualifier("RTUProtocolCmdHandleServiceImpl")
    private CurrencyProtocolCmdHandleService rtuProtocolCmdHandleService;

    @Resource
    private TCPIPCmdHandleService tcpipCmdHandleService;

    /**
     * 通用指令发送-初始化所有硬件IP
     */
    @Override
    public void initAllHardware() {
        //查询硬件列表
        List<PortComm> allProtocolComm =
                protocolParamService.findAllProtocolComm();
        List<PortSocket> allProtocolSocket =
                protocolParamService.findAllProtocolSocket();

        //添加串口 初始化RTU
        if (allProtocolComm != null && !allProtocolComm.isEmpty()) {
            for (PortComm portComm : allProtocolComm) {
                if (portComm.getStatus() == Status.ENABLE) {
                    rtuProtocolCmdHandleService.addIpPort(new SendReceiverData(portComm.getPort()));
                }
            }
        }
        //添加串口 初始化TCP
        if (allProtocolSocket != null && !allProtocolSocket.isEmpty()) {
            for (PortSocket portSocket : allProtocolSocket) {
                if (portSocket.getStatus() == Status.ENABLE) {
                    if (portSocket.getServerType().equals("client")) {
                        tcpProtocolCmdHandleService.addIpPort(new SendReceiverData(
                                portSocket.getServerIp() + ":" + portSocket.getServerPort()));
                    } else if (portSocket.getServerType().equals("server")) {
                        tcpipCmdHandleService.addTCPIp(new SendReceiverData(
                                portSocket.getServerIp() + ":" + portSocket.getServerPort()));
                    } else {
                        //s7相关操作
                        log.info("此处初始化连接S7");
                    }
                }
            }
        }
    }

    /**
     * 发从指令 从opt中获取
     *
     * @param commonParamOptReq 发送指令具备的所有参数
     */
    @Override
    public void sendCmdFromOpt(CommonParamOptReq commonParamOptReq) {
        CurrencyProtocolWriteReq req = new CurrencyProtocolWriteReq();
        req.setId(commonParamOptReq.getProjectConfiguration().getSlaveAddress());
        String address = commonParamOptReq.getProjectConfiguration().getAddress();
        if (address.contains(".")) {
            String addressBefore = address.substring(0, address.indexOf("."));
            int i = Integer.parseInt(addressBefore) / 2;
            String s = BaseConversionTools.intToShortHex(i);
            req.setStartAddress(s);
        } else {
            int i = Integer.parseInt(address) / 2;
            String s = BaseConversionTools.intToShortHex(i);
            req.setStartAddress(s);
        }
        String value = commonParamOptReq.getProjectConfiguration().getValue();
        if (value.length() <= 4) {
            if (value.contains(".")) {
                float v = Float.parseFloat(value);
                String hexString = BaseConversionTools.intToShortHex((int) v);
                req.setWriteValue(hexString);
            } else {
                int valueDec = Integer.parseInt(value);
                String hexString = BaseConversionTools.intToShortHex(valueDec);
                req.setWriteValue(hexString);
            }
        }

        String port = commonParamOptReq.getCheckPort();
        String code = commonParamOptReq.getCheckCode();

        int valueType = commonParamOptReq.getProjectConfiguration().getValueType();
        String dbAddress = commonParamOptReq.getProjectConfiguration().getDbAddress();
        //modbus_tcp_opt
        if (commonParamOptReq.getCheckFunction().equals(modbusTcp)) {
            switch (code) {
                case "05" -> {
                    tcpProtocolCmdHandleService.writeFunctionCode05(port, req);
                }
                case "06" -> {
                    tcpProtocolCmdHandleService.writeFunctionCode06(port, req);
                }
                case "10" -> {
                    tcpProtocolCmdHandleService.writeFunctionCode10(port, req);
                }
                case "15" -> {
                    tcpProtocolCmdHandleService.writeFunctionCode15(port, req);
                }
                default -> log.info("tcp-未找到对应的功能码");
            }
        } //modbus_rtu_opt
        else if (commonParamOptReq.getCheckFunction().equals(modbusRtu)) {
            switch (code) {
                case "05" -> {
                    rtuProtocolCmdHandleService.writeFunctionCode05(port, req);
                }
                case "006" -> {
                    rtuProtocolCmdHandleService.writeFunctionCode06(port, req);
                }
                case "10" -> {
                    rtuProtocolCmdHandleService.writeFunctionCode10(port, req);
                }
                case "15" -> {
                    rtuProtocolCmdHandleService.writeFunctionCode15(port, req);
                }
                default -> log.info("rtu-未找到对应的功能码");
            }
        } //s7
        else if (commonParamOptReq.getCheckFunction().equals(s7)) {
            switch (valueType){
                case 1 ->{
                    s7PLC.writeBoolean(dbAddress + "." + address,value.equals("1"));
                }
                case 2 ->{
                    s7PLC.writeInt16(dbAddress + "." + address, Short.parseShort(value));
                }
                case 3 ->{
                    s7PLC.writeFloat32(dbAddress + "." + address, Float.parseFloat(value));
                }
            }
            log.info("S7:{}", commonParamOptReq.getCheckFunction());
        } //自定义协议或者Server端
        else {
            log.info("自定义协议，或者当前传输错误:{}", commonParamOptReq.getCheckFunction());
        }
    }

    @Resource
    public S7PLC s7PLC;



}
